/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.pokemon.dao;

import com.pokemon.entities.Trainer;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Repository;

/**
 *
 * @author Martin Fabian
 */
@Component
@Repository("TrainerDAOJpa")
public class TrainerDAOJpa implements TrainerDAO{

    @PersistenceContext()
    private EntityManager em;
    
    public void setEm(EntityManager em) {
        this.em = em;
    }
    
    public void setEntityManagerFactory(EntityManagerFactory entityManagerFactory){
        //this.entityManagerFactory = entityManagerFactory;
    }
    
    
    public void addTrainer(Trainer trainer) {
        if ((trainer == null) || (trainer.getId() != null)) {
            throw new IllegalArgumentException("Trainer must be non-null and its id must be null");
        }
       
        em.persist(trainer);
        
    }

    
    public Trainer getTrainer(Long id) {
        if (id == null) {
            throw new IllegalArgumentException("Trainer id must be non-null");
        }
        
        Trainer trainer = em.find(Trainer.class, id);

        return trainer;
    }

    
    public void updateTrainer(Trainer trainer) {
        if ((trainer == null) || (trainer.getId() == null)) {
            throw new IllegalArgumentException("Trainer and its id must be non-null");
        }

        
        //em.persist(trainerToUpdate);
        em.merge(trainer);

    }

    
    public void removeTrainer(Trainer person) {
        if ((person == null) || (person.getId() == null)) {
            throw new IllegalArgumentException("Trainer and its id must be non-null");
        }
        
        Trainer trainerToRemove = em.find(Trainer.class, person.getId());
       
        em.remove(trainerToRemove);
        
       
    }

    
    public List<Trainer> getAllTrainers() {
        
        Query query = em.createQuery("SELECT e FROM Trainer e");
        return (List<Trainer>) query.getResultList();
    }
    
}
